﻿using BlogSystem.Common.Config;
using BlogSystem.Exception;
using Microsoft.EntityFrameworkCore;

namespace BlogSystem.Data.Repository.RepositoryImpl;

public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class,new()
{
    
    private readonly DataBaseContext _databaseContext;

    public BaseRepository(DataBaseContext databaseContext)
    {
        _databaseContext = databaseContext;
    }
    
    
    public async Task<bool> Add(TEntity entity)
    {
        var res= await _databaseContext.Set<TEntity>().AddAsync(entity);
        await _databaseContext.SaveChangesAsync();
        return res==null?false:true;
    }
    
    public IQueryable<TEntity> GetAllByPage()
    {
        return _databaseContext.Set<TEntity>();
    }
    
    public async Task<TEntity>  GetById(int id)
    {
        return  await _databaseContext.Set<TEntity>().FindAsync(id);
    }
    
    public  async Task<bool>  Update(TEntity entity)
    {
        try
        {
            var res = _databaseContext.Set<TEntity>().Update(entity);
            await _databaseContext.SaveChangesAsync();
            return res==null?false:true;
        }
        catch (System.Exception e)
        {
            throw new BusinessException($"An error occurred: {e.Message}");
        }
        return false;
    }
    
    
}